/**
 * 上传图片或者视频 extension
 */
$J(function() {
	//创建参数
	$J(".upload").on("mouseover","img[id^='target']",function(){
	    xsize = 16,
	    ysize = 10;
	    //标示当前操作的图片
	    var tagId=$J(this).attr("id");
	    $J("#tag").val(tagId.substring(6,tagId.length));
		$J(this).Jcrop({
			minSize:[160,100],
			maxSize:[160*3.3,100*3.3],
			onChange: updatePreview,
			onSelect: updatePreview,
			aspectRatio: xsize / ysize,
		});
	});
    
    function updatePreview(c) {	
    	if(c.w<160 || c.h<90) {
    		return;
    	}
    	
    	var tag=$J("#tag").val();
        var img=$J("#target"+tag);
        var width=img.width();
        var height=img.height();
    	var naW=$J("#naW"+tag).val();
		var naH=$J("#naH"+tag).val();
		//对比图片原始高宽度的缩放比例
		var w_radio=decimal(naW/width,3);
		var h_radio=decimal(naH/height,3);
		//设置图片x,y,w,h值 
		$J("#x"+tag).val(c.x*w_radio);
		$J("#y"+tag).val(c.y*h_radio);
		$J("#w"+tag).val(c.w*w_radio);
		$J("#h"+tag).val(c.h*h_radio);
    };
    
	/*
	 * 选择文件时校验文件合法性 
	 */
	$J('.upload').on('change', 'input[name=file]', function() {
		// 隐藏原有图片
		$J('.originalImg').hide();
		
		if (validateFile(this.files[0]) == false) {
			 $J(this).after($J(this).clone().val(""));
			 $J(this).remove();
			 return false;
		}
	});
	/*
	 * 上传按钮触发事件
	 */
	$J("#upload_btn").click(function() {
		var input_files = $J("input[name=file]");
		if (input_files.length == 0) {
			alert("请选择上传文件");
			return;
		}
		// 遍历后异步上传
		$J.each(input_files, function(index, input_item) {
			if (input_item.files.length > 0) {
				var file = input_item.files[0];
				if (validateFile(file) == false) {
					file.after(file.clone().val(""));
					file.remove();
					return;
				}
				var fileId = $J(input_item).attr("id");
				ajaxFileUpload(fileId);
				getProcess(fileId);
			}
		})
	});

	function validateFile(file) {
		if (!file) {
			return;
		}
		if (file.type == null || file.type == '') {
			alert("不支持的文件格式");
			return false;
		}
		if (!picAllow(file) && !videoAllow(file)) {
			alert("不支持的文件格式 请上传有效的图片或者视频");
			return false;
		}
	}
	/*
	 * 取消上传
	 */
	$J('.upload').on('click', 'div[id^=cancel]', function() {
		var id=$J(this).attr("id");
		var id_num = id.substring(id.length - 1, id.length + 1);
		var obj=$J(this).parent().find("file"+id_num);   
		obj.outerHTML=obj.outerHTML; 
		$J(this).parent().remove();
	});
	
	/*
	 * 生成多附件上传框
	 */
	var count = 1;
	$J("#addChild").click(function(){
		count++;
		var p = $J("#multidiv1");
		var mdiv = p.clone(true);
		mdiv.find("#text1").attr("id", "text" + count);
		mdiv.find("#progress1").attr("id", "progress" + count);;
		mdiv.find("#progress-bar1").attr("id", "progress-bar" + count);
		mdiv.find("#url1").attr("id", "url" + count);
		mdiv.find("#type1").attr("id", "type" + count);
		mdiv.find("#preview1").attr("id", "preview" + count).html('');
		mdiv.find("#file1").attr("id", "file" + count);
		mdiv.find("#x1").attr("id", "x" + count);
		mdiv.find("#y1").attr("id", "y" + count);
		mdiv.find("#w1").attr("id", "w" + count);
		mdiv.find("#h1").attr("id", "h" + count);
		mdiv.find("#cancel1").attr("id", "cancel" + count);
		mdiv.find("#naW1").attr("id", "naW" + count);
		mdiv.find("#naH1").attr("id", "naH" + count);
		mdiv.find("#imgItem1").attr("id", "imgItem" + count);
		mdiv.show();
//		p.after(mdiv);
		$J("#mm").append(mdiv);
	}); 
	
	/*
	 * 上传
	 */
	function ajaxFileUpload(fileId) {
		var id_num = fileId.substring(fileId.length - 1, fileId.length + 1);
		var params = {
				'x' : $J("#x" + id_num).val(),
				'y' : $J("#y" + id_num).val(),
				'w' : $J("#w" + id_num).val(),
				'h' : $J("#h" + id_num).val()
		};
		jQuery.ajaxFileUpload({
			url : window.baseUrl + '/fileUpload/upload',
			secureuri : false,
		    data:params,  
			fileElementId : fileId,
			dataType : 'json',
			success : function(data, status) {
				var status = data.status;
				var id_num = fileId.substring(fileId.length - 1, fileId.length + 1);
				if (status == false) {
					$J("#text" + id_num).html('<span class="ajax_msg_faild">' + '上传失败：' + data.msg + '</span>');
				} else {
					var url = data.data.url
					$J("#url" + id_num).val(url);
					$J("#type" + id_num).val(data.data.type);
					$J("#text" + id_num).html("上传成功");
					$J("#" + fileId).show();
				}
			},
			error : function(data, status, e) {
				alert(false);
			}
		});
	}
	/*
	 * 获取上传进度信息
	 */
	function getProcess(fileId) {
		var id_num = fileId.substring(fileId.length - 1, fileId.length + 1);
		var url = window.baseUrl + "/fileUpload/getProcess";
		var params = { 'num' : id_num };
		$J.ajax({
			type : 'get',
			url : url,
			dataType : 'json',
			async : true,
			data : params,
			cache : false,
			success : function(data) {
				var percent = data.data;
				percent = parseInt(percent);
				// 进度条100%只代表上传到服务器的进度 不代表上传到第三方云存储的进度 所以减一 。在ajax上传成功后显示上传成功
				if (percent == 100) {
					$J("#text" + id_num).html(
							"正在上传，进度：" + parseInt(percent - 1) + "%");
				} else {
					$J("#text" + id_num).html("正在上传，进度：" + percent + "%");
					setTimeout("req_timeout()", 1000);
				}
				$J("#progress-bar" + id_num).animate({
					width : percent + "%"
				}, 200);
				
			}
		});
		var id_num = fileId.substring(fileId.length - 1, fileId.length + 1);
		$J("#file"+id_num).hide();
	}
	
	/*
	 * 图片文件合法性校验
	 */
	function picAllow(file) {
		if (!file) {
			return;
		}
		var picAllowType = [ "jpeg", "jpg", "png", "bmp" ];
		var extension = file.type.substring(file.type.indexOf("/") + 1,
				file.type.length);
		var allow = false;
		$J.each(picAllowType, function(index, value) {
			if (value == extension) {
				allow = true;
			}
		});
		return allow;
	}
	/*
	 * 视频文件合法性校验
	 */
	function videoAllow(file) {
		if (!file) {
			return;
		}
		var videoAllowType = [ "avi", "mp4", "flv" ];
		var extension = file.type.substring(file.type.indexOf("/") + 1,
				file.type.length);
		var allow = false;
		$J.each(videoAllowType, function(index, value) {
			if (value == extension) {
				allow = true;
			}
		});
		return allow;
	}
	
	// 图片上传预览
	$J('.upload').on('change', '.file', function() {
		var input_file=this;
		var is_preview = picAllow(input_file.files[0]);
		if (!(is_preview && input_file.files && input_file.files[0])) {
			return;
		}
		var MAXWIDTH = 160*3.3;
		var MAXHEIGHT =100*3.3;
		var input_id = $J(input_file).attr("id");
		id_num = input_id.substring(input_id.length - 1, input_id.length + 1);
		
		$J("#preview" + id_num).html(" ");
		var div = document.getElementById("preview" + id_num);
		div.innerHTML = "<img id=target"+id_num+">";
		var img = document.getElementById('target'+id_num);
		img.onload = function() {
			$J("#naW"+id_num).val(img.naturalWidth);
			$J("#naH"+id_num).val(img.naturalHeight);
			var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth,img.offsetHeight);
			img.width = rect.width;
			img.height =rect.height;
			img.style.marginTop = rect.top + 'px';
		}
		var reader = new FileReader();
		reader.onload = function(evt) {
			img.src = evt.target.result;
		}
		reader.readAsDataURL(input_file.files[0]);
		
	});
	
	function clacImgZoomParam(maxWidth, maxHeight, width, height) {
		var param = {
			top : 0,
			left : 0,
			width : width,
			height : height
		};
		if (width > maxWidth || height > maxHeight) {
			rateWidth = width / maxWidth;
			rateHeight = height / maxHeight;
	
			if (rateWidth > rateHeight) {
				param.width = maxWidth;
				param.height = Math.round(height / rateWidth);
			} else {
				param.width = Math.round(width / rateHeight);
				param.height = maxHeight;
			}
		}
	
		param.left = Math.round((maxWidth - param.width) / 2);
		param.top = Math.round((maxHeight - param.height) / 2);
		return param;
	}
	//对多位小数进行四舍五入
	//num是要处理的数字  v为要保留的小数位数
	function decimal(num,v){
		var vv = Math.pow(10,v);
		return Math.round(num*vv)/vv;
	}
});